package com.cxh.controller.robot;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.GsonBuilder;
import com.cxh.entity.*;
import com.cxh.util.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.cxh.base.BaseController;
import com.cxh.entity.RobotInfo;
import com.google.gson.Gson;
import com.shimne.util.NumberUtil;
import com.shimne.util.ObjectUtil;
import com.shimne.util.StringUtil;

@Controller
@RequestMapping(value = "/action/lodJson1")
public class JsonAction  extends BaseController {
	
	private String speak = "";// 返回语言
	private String url = "";
	private int msgType = 2; // 2默认 1.场景模式 2.对答模式 
	private String msg = "返回成功";	//日志说明
	private int flag = 0; // 返回标志
	private int scene = 0;	//场景类型
	private int skill = 0;
	private int status = 1;	//返回状态  0、匹配失败  1、匹配成功  2、未匹配到内容  3、匹配多项
	
	//全局匹配
	@RequestMapping(value = "/loadMess")
	public void loadMess(HttpServletRequest request, HttpServletResponse response,String code,String question){
		this.innitData();
		String json = "";
		this.msgType = 1;
		//1.根据机器人编码获得机器人对象
		/*String code = request.getParameter("code");
		String question = String.valueOf(request.getParameter("answer"));*/
		RobotInfo robotInfo = robotInfoService.loadByCode(code);
		System.out.println(question);
		//获得匹配到的集合
		List<Map<String,Object>> list = skillsOptionService.LoadSkills(question, robotInfo.getId());
		if(list != null && list.size() == 1){
			Map<String,Object> map = list.get(0);
			skill = Integer.parseInt(map.get("skillid")+"");
			scene = Integer.parseInt((CommonUtility.isEmpty(map.get("type"))?"0":map.get("type"))+"");
			SkillsOption option = new SkillsOption();
			Map<String, Object> cmdMap = new HashMap<String, Object>();
			option =skillsOptionService.findOptionBySkill(Integer.parseInt(map.get("skillid")+""),question);
			option = ObjectUtil.isNull(option)?skillsOptionService.loadById(Integer.parseInt(map.get("optionid")+"")):option;
			speak = option.getContents();
			if(option.getNettype() == 0){
				//内网链接需要配置路径
				if(!StringUtil.isEmpty(option.getUrl())){
					url = sysVarsService.loadUrlByName(ComUtil.SYSTEM_PATH) +
							sysVarsService.loadUrlByName(ComUtil.SYSINFO_VIRTUALPATH) +
							sysVarsService.loadUrlByName(ComUtil.HTML_PATH) +
							option.getUrl();
				}
			}else{
				//外网路径直接等于
				url = option.getUrl();
			}
			cmdMap = skillsOptionService.loadByCmd(option.getId());
			Map<String,Object> resultMap = new HashMap<String,Object>();

			resultMap.put("scene", this.scene);
			resultMap.put("skill", this.skill);
			resultMap.put("msgType", this.msgType);
			resultMap.put("flag", flag);
			resultMap.put("msg", msg);
			resultMap.put("speak",speak);
			resultMap.put("skillList", new Object[]{});
			resultMap.put("url",url);
			resultMap.put("set", cmdMap);
			json = JSON.toJSONString(resultMap);

			super.ajaxOutput(response, json);
		}else if(list!=null && list.size()>1){
			//组织集合返回
			List<Map<String,Object>> resultlist=new ArrayList<Map<String,Object>>();
			for(Map<String,Object> obj:list){
				Map<String,Object> objMap=new HashMap<String,Object>();
				objMap.put("title", obj.get("title"));
				objMap.put("skillId",obj.get("skillid"));
				resultlist.add(objMap);
			}
			Map<String,Object> resultMap = new HashMap<String,Object>();
			resultMap.put("scene", this.scene);
			resultMap.put("skill", this.skill);
			resultMap.put("msgType", this.msgType);
			resultMap.put("flag", flag);
			resultMap.put("msg", msg);
			speak = "已为您找到相关业务，请问你要办理第几项？";
			resultMap.put("speak", speak);
			resultMap.put("skillList", resultlist);
			resultMap.put("url",url);
			resultMap.put("set", new Object());
			json=JSON.toJSONString(resultMap);
			
			ajaxOutput(response, json);
			
		}else{
			//未匹配到数据转发到基础问答处理
				this.loadSoundQuAn(request, response);
		}
				
	}
	
	/**
	 * 匹配基础问答
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/loadSoundQuAn")
	public void loadSoundQuAn(HttpServletRequest request, HttpServletResponse response){
		this.innitData();
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("skill", 0);
		resultMap.put("scene",0);
		resultMap.put("msgType",2);
		Map<String, Object> cmdMap = new HashMap<String, Object>();	//命令集集合
		List<Map<String,Object>> objectList = new ArrayList<Map<String,Object>>(); //匹配项
		// 问题
		String answer =String.valueOf(request.getAttribute("answer"));
		try {
			// 机器人编码
			String code = request.getParameter("code");
			// 根据编码获取机器人
			RobotInfo robot = robotInfoService.loadByCode(code);
			
			// 匹配最多的次数
			int maxNum = 0;
			//通过机器人查询
			List<SoundQu>  soundList=soundQuService.loadByCode(code);
			SoundQu soundQu = this.getByQuestionsByQustion(soundList,answer);
			if(ObjectUtil.isNull(soundQu)){
				// 获取机器人机构编码
				int orgId = 0;
				if(!CommonUtility.isEmpty(robot.getOrg())){
					orgId = robot.getOrg();
				}
				soundList=soundQuService.loadAllByOrg(orgId);
				soundQu = this.getByQuestionsByQustion(soundList,answer);
				
			}
			
			if(!CommonUtility.isEmpty(soundQu) && !CommonUtility.isEmpty(soundQu.getFlg()) && soundQu.getFlg()==1){
				resultMap.put("msgType",1);
			}
			
				// 找到最大匹配项
			if(!ObjectUtil.isNull(soundQu)){

				List<Map<String, Object>> lsq = soundQuAnService.loadByQu(soundQu.getId());
				if(!ObjectUtil.isNull(lsq) && lsq.size() > 0){
					int num = lsq.size();
					Random random = new Random();
					// 随机选择一个答案
					num = random.nextInt(num);
					Map<String, Object> sqa = lsq.get(num);
					this.speak = String.valueOf(sqa.get("contents"));
					this.status = 1;
					if(!ObjectUtil.isNull(sqa.get("url")) && !ObjectUtil.isEmpty(sqa.get("url"))){
						this.url = sysVarsService.findByName(ComUtil.SYSTEM_PATH).getValues()+ 
								   sysVarsService.findByName(ComUtil.SYSINFO_VIRTUALPATH).getValues()+
								   sysVarsService.findByName(ComUtil.HTML_PATH).getValues() + sqa.get("url");
					}
					// 绑定命令集ID
					int cmdId = ObjectUtil.isNull(sqa.get("collection"))?0:Integer.parseInt(String.valueOf(sqa.get("collection")));
					if(cmdId > 0){
						String mapUrl = sysVarsService.findByName(ComUtil.SYSTEM_PATH).getValues()+ 
								        sysVarsService.findByName(ComUtil.SYSINFO_VIRTUALPATH).getValues()+
								        sysVarsService.findByName(ComUtil.MAP_PATH).getValues();
						
						// 获取命令集
						cmdMap = cmdCollectionService.loadCmdMap(cmdId, mapUrl);
					}
					
				}else{
						this.flag = 1;
						this.msg = "暂无消息";
						this.status = 2;
//					}
				}
				
			}else{
					request.getRequestDispatcher("/action/lodJson/chat").forward(request, response);
			}
				
			
		} catch (Exception e) {
			e.printStackTrace();
			this.flag = 2;
			this.msg = "返回数据失败！";
			this.status=0;
			
		}
		resultMap.put("flag", this.flag);
		resultMap.put("set", cmdMap);
		resultMap.put("speak",this.speak);
		resultMap.put("msg", this.msg);
		resultMap.put("url", this.url);
		resultMap.put("skillList", objectList);
		
		String json = JSON.toJSONString(resultMap);
		super.ajaxOutput(response, json);
	}

	/**
	 * 
	 * @param soundList
	 * @param qeustion
	 * @return
	 */
	public static SoundQu getByQuestionsByQustion(List<SoundQu>  soundList,String qeustion){
		int length=0;
		SoundQu soundQu = null;
		if(!ObjectUtil.isNull(soundList) && soundList.size() > 0){
			for(SoundQu sq : soundList){
				if(ObjectUtil.isNull(sq) || StringUtil.isTrimEmpty(sq.getKeywords())){
					continue;
				}
				String keyWords=sq.getKeywords().replaceAll("，", ",");
				String[] keywords = keyWords.split(",");
				StringBuffer str = null;
				if(!ObjectUtil.isNull(keywords) && keywords.length>0){
					str = new StringBuffer("(");
					int objLength = keywords.length;
					
					for(int i=0;i<objLength;i++){
						str.append(keywords[i]);
						if(i<objLength-1){
							str.append("|");
						}
					}
					str.append(")");
					if(StringUtils.checkRegular(str.toString(), qeustion)){
						String objString=StringUtils.getStringValue(str.toString(), qeustion);
						if(objString.length()>length){
							soundQu=sq;
							length=objString.length();
						}
						
					}
				}
				
			}
			
		}
		return soundQu;
	}
	
	/**
	 * 将返回参数重置
	 */
	private void innitData(){
		url = "";
		msgType = 2; // 2默认 1.场景模式 2.对答模式 
		msg="返回成功";	//日志说明
		flag = 0; // 返回标志
		scene=0;	//场景类型
		skill=0;
		this.speak="";
		this.status=1;
	}
}
